<template>
  <!-- <a-modal
    :visible="visible"
    :afterClose="hanldeAfterClose"
    @cancel="handleCancel"
    @ok="handleOk"
    :confirmLoading="isSubmiting"
    :okText="isForm ? '提交' : '确定'"
    width="1400px"
    title="数据异动"
  > -->
  <a-spin :spinning="spinning">
    <page-header-wrapper :title="`申请编号：${browserCacheObj.ApplyNo || ''}`">
      <template v-slot:extra v-if="browserCacheObj.isForm">
        <a-button type="primary" shape="round" @click="handleOk">确认修改</a-button>
        <a-button type="" shape="round" @click="handleCancel">取消修改</a-button>
      </template>
      <a-tabs v-model="activeKey" style="background: #fff; padding: 20px" @change="handleTabChange">
        <a-tab-pane key="info" tab="保障用户基本信息">
          <info v-if="!browserCacheObj.isForm" :proposerID="browserCacheObj.id"></info>
          <div v-else>
            <infoFrom v-if="!spinning" ref="info" :isForm="false" :data="proposerData"></infoFrom>
          </div>
        </a-tab-pane>
        <a-tab-pane key="change" tab="信息异动" forceRender>
          <a-form v-if="browserCacheObj.isForm" :form="form" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
            <a-row :gutter="16" type="flex">
              <a-col :span="8">
                <a-form-item label="原核定保障人数">
                  <a-input disabled v-decorator="['CityVfyNumber']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="原核定人均面积">
                  <a-input disabled v-decorator="['CityVfyAreaPer']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="原核定人均收入">
                  <a-input disabled v-decorator="['CityVfyIncome']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="原补贴">
                  <span class="text-warning">{{ $isEmpty(Number(SMoney)) ? SMoney : '暂无补贴金额' }}</span>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16" type="flex">
              <a-col :span="8">
                <a-form-item label="异动类型">
                  <a-select
                    v-decorator="['AlterType', { rules: [{ required: true, message: '请选择异动类型' }] }]"
                    placeholder="请选择异动类型"
                    :options="typeOptions"
                    @change="handleTypeChange"
                  ></a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-show="form.getFieldValue('AlterType') === '退出'">
                <a-form-item label="退出原因（类别）">
                  <a-switch
                    v-decorator="['AlterReasonQuit', { initialValue: false, valuePropName: 'checked' }]"
                    checked-children="中天共有产权退出"
                    un-checked-children="中天共有产权退出"
                  ></a-switch>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-show="form.getFieldValue('AlterType') === '变更'">
                <a-form-item label="变更原因（类别）">
                  <a-select
                    placeholder="请选择变更原因"
                    v-decorator="['AlterReasonChange', { initialValue: [] }]"
                    mode="multiple"
                    :options="reasonOptions"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="异动原因" :labelCol="{ span: 2 }" :wrapperCol="{ span: 22 }">
                  <a-textarea
                    v-decorator="['AlterInfo', { rules: [{ required: true, message: '请输入异动原因' }] }]"
                    placeholder="请输入异动原因"
                  ></a-textarea>
                </a-form-item>
              </a-col>
              <a-col :span="24" v-show="form.getFieldValue('AlterType') === '变更'">
                <a-form-item label="历史异动原因" :labelCol="{ span: 2 }" :wrapperCol="{ span: 22 }">
                  <s-table
                    ref="table"
                    size="small"
                    rowKey="ID"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onTableSelectChange }"
                    :columns="tableColumns"
                    :data="tableData"
                    :showPagination="false"
                  ></s-table>
                  <span class="text-warning" slot="extra">Tips：支持多选</span>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="经办人">
                  <a-input disabled v-decorator="['AlterExecutor']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="异动时间">
                  <a-input disabled v-decorator="['AlterDate']"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-descriptions v-else class="p-x-16" :column="2" bordered>
            <a-descriptions-item label="异动类型">{{ alterDetail.AlterType || '/' }}</a-descriptions-item>
            <a-descriptions-item label="变更原因">{{ alterDetail.AlterReason || '/' }}</a-descriptions-item>
            <a-descriptions-item label="异动原因" :span="2">{{
              alterDetail.AlterInfo || alterDetail.YdReason || '/'
            }}</a-descriptions-item>
            <!-- <a-descriptions-item label="历史异动原因" :span="2"> 历史异动原因 </a-descriptions-item> -->
            <a-descriptions-item label="经办人">{{ alterDetail.AlterExecutor || '/' }}</a-descriptions-item>
            <a-descriptions-item label="异动日期">{{
              alterDetail.AlterDate | moment('YYYY-MM-DD')
            }}</a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
        <a-tab-pane key="report" tab="调查报告与机构意见">
          <report v-if="tabClick[1]" :proposerID="browserCacheObj.id" />
        </a-tab-pane>
        <a-tab-pane key="infoLog" tab="信息变更记录">
          <infoLog v-if="tabClick[2]" :proposerID="browserCacheObj.id" />
        </a-tab-pane>
        <a-tab-pane key="houseLog" tab="房屋分配记录">
          <houseLog v-if="tabClick[3]" :proposerID="browserCacheObj.id" />
        </a-tab-pane>
      </a-tabs>
    </page-header-wrapper>
  </a-spin>
  <!-- </a-modal> -->
</template>

<script>
import { STable } from '@/components'
import info from '@/views/commonViews/components/info'
// import infoFrom from './infoFrom'
import houseLog from '@/views/commonViews/components/houseLog'
import infoLog from '@/views/commonViews/components/infoLog'
import report from '@/views/commonViews/components/report'
import infoFrom from '@/views/CommunityReviewManagement/applicationForm/infoChange'
import { getNewProposerbyID, postProposerExamine } from '@/api/common'
import { postApplication } from '@/api/communityReviewManagement'
import { getHousesCountSJ, getAlterHistoryList, getAlterDetail } from '@/api/cityReviewAndManage'
import cloneDeep from 'lodash.clonedeep'
import moment from 'moment'
export default {
  // name: 'cityComplexInquireList',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {},
    },
    // isForm: {
    //   type: Boolean,
    //   default: false,
    // },
  },
  components: {
    info,
    houseLog,
    infoLog,
    report,
    infoFrom,
    STable,
  },
  // watch: {
  //   visible(n) {
  //     if (n) {
  //       this.fetchData()
  //     }
  //   },
  // },
  mounted() {
    this.fetchData()
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'dataChange' }),
      isSubmiting: false,
      browserCacheObj: {},
      activeKey: 'info',
      tabClick: [true, false, false, false],
      spinning: false,
      proposerData: {},
      SMoney: '',
      selectedRowKeys: [],
      alterDetail: {},
      tableColumns: [
        {
          title: '申请编号',
          align: 'center',
          dataIndex: 'ApplyNo',
        },
        {
          title: '异动类型',
          align: 'center',
          dataIndex: 'AlterType',
        },
        {
          title: '内容',
          align: 'center',
          dataIndex: 'AlterInfo',
        },
        {
          title: '操作人',
          align: 'center',
          dataIndex: 'AlterPerson',
        },
        {
          title: '操作时间',
          align: 'center',
          dataIndex: 'AlterDate',
          customRender: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
        },
      ],
      tableData: (parameter) => {
        this.selectedRowKeys = []
        return getAlterHistoryList({
          // ProposerID: this.data.ID,
          ProposerID: this.browserCacheObj.id,
        }).then((res) => {
          return {
            data: res,
            total: res.length,
          }
        })
      },
      typeOptions: [
        {
          label: '退出',
          value: '退出',
        },
        {
          label: '变更',
          value: '变更',
        },
        {
          label: '更正',
          value: '更正',
        },
      ],
      reasonOptions: [
        {
          label: '户主变更',
          value: '户主变更',
        },
        {
          label: '人口变更',
          value: '人口变更',
        },
        {
          label: '社区调整',
          value: '社区调整',
        },
        {
          label: '面积变更',
          value: '面积变更',
        },
        {
          label: '收入变更',
          value: '收入变更',
        },
        {
          label: '梯度变化',
          value: '梯度变化',
        },
        {
          label: '区级调整',
          value: '区级调整',
        },
        {
          label: '实物变更',
          value: '实物变更',
        },
      ],
    }
  },
  methods: {
    onTableSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTypeChange(e) {
      // if (e === '变更') {
      //   this.$refs.table.refresh(true)
      // }
    },
    handleTabChange(key) {
      const tabList1 = [
        { key: 'info', tab: '保障用户基本信息' },
        { key: 'report', tab: '调查报告与机构意见' },
        { key: 'infoLog', tab: '信息变更记录' },
        { key: 'houseLog', tab: '房屋分配记录' },
      ]
      const index = tabList1.findIndex((e) => e.key === key)
      this.tabClick[index] = true
    },
    fetchData() {
      this.browserCacheObj = JSON.parse(localStorage.getItem('browserCacheView'))
      if (this.browserCacheObj.isForm) {
        const getProposer = getNewProposerbyID({
          // ProposerID: this.data.ID,
          ProposerID: this.browserCacheObj.id,
        })
        const hasHouse = getHousesCountSJ({
          // idcards: this.data.IDCard,
          idcards: this.browserCacheObj.IDCard,
        })
        this.spinning = true
        // Promise.all([hasHouse, getProposer])
        getNewProposerbyID({
          // ProposerID: this.data.ID,
          ProposerID: this.browserCacheObj.id,
        })
          .then((res) => {
            // this.$info({
            //   title: '提示',
            //   content: res[0][0].msg,
            // })
            const IDCardArr = []
            for (let i = 0; i < res.proposerdetail.length; i++) {
              IDCardArr.push(res.proposerdetail[i].IDCards)
            }
            // for (let i = 0; i < res.proposerfdetail.length; i++) {
            //   IDCardArr.push(res.proposerfdetail[i].FIDCard)
            // }
            // 查不动产信息
            // this.hasHouse(IDCardArr.join(','))
            getHousesCountSJ({
              // idcards: this.data.IDCard,
              idcards: IDCardArr.join(','),
            })
              .then((ress) => {
                this.$info({
                  title: '提示',
                  content: ress[0].msg,
                })
              })
              .finally(() => {
                this.spinning = false
              })
            res.RegionNo = Number(res.RegionNo)
            res.TownshipNo = Number(res.TownshipNo)
            this.proposerData = res
            this.proposerData.proposerdetail[0].isapplicant = true
            this.$nextTick(() => {
              this.form.setFieldsValue({
                AlterExecutor: this.$store.getters.nickname,
                AlterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                // AlterInfo: this.data.YdReason,
                AlterInfo: this.browserCacheObj.YdReason,
                CityVfyNumber: res.CityVfyNumber,
                CityVfyAreaPer: res.CityVfyAreaPer,
                CityVfyIncome: res.CityVfyIncome,
              })
              this.SMoney = res.SMoney
            })
          })
          .finally(() => {
            // this.spinning = false
            this.$nextTick(() => {
              this.form.setFieldsValue({
                AlterExecutor: this.$store.getters.nickname,
                AlterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                // AlterInfo: this.data.YdReason,
                AlterInfo: this.browserCacheObj.YdReason,
              })
            })
          })
      } else {
        getAlterDetail({
          // ProposerID: this.data.ID,
          ProposerID: this.browserCacheObj.id,
        }).then((res) => {
          this.alterDetail = res
        })
      }
    },
    close() {
      this.form.resetFields()
      this.$emit('update:visible', false)
      this.$emit('update:data', {})
      this.activeKey = 'info'
      this.tabClick = [true, false, false, false]
      this.proposerData = {}
      this.SMoney = ''
    },
    handleCancel() {
      this.close()
      this.hanldeAfterClose()
      this.$multiTab.closeCurrentPage()
    },
    handleOk() {
      if (!this.browserCacheObj.isForm) {
        this.handleCancel()
      } else {
        const infoSubmit = this.$refs.info.handleSubmit()
        const changeSubmit = new Promise((resolve, reject) => {
          this.form.validateFields((err, values) => {
            if (!err) {
              resolve(values)
            } else {
              // reject(new Error('信息异动未填写完整'))
              this.$message.error({
                text: '信息异动未填写完整',
              })
            }
          })
        })
        Promise.all([infoSubmit, changeSubmit])
          .then((res) => {
            const applicationData = cloneDeep(this.proposerData)
            Object.assign(applicationData, res[0])
            applicationData.proposerdetail.forEach((element) => {
              delete element.LiveDistrictAddressArr
              delete element.censusRegister
              if (['低保', '低收入'].includes(element.IfLowObjects)) {
                element.IfLowObjects = '有'
              } else {
                element.IfLowObjects = '无'
              }
              if (Array.isArray(element.GroupOfApplicants)) {
                element.GroupOfApplicants = element.GroupOfApplicants.join(',')
              }
            })
            // 2023-09-11 由于甲方单位工作需求发生变更，取消民族接口查询功能
            // if (res[1].Alientype !== '退出') {
            //   this.$loading.show({
            //     tip: '查询是否有死亡成员中，请稍后...'
            //   })
            //   const personMap = new Map()
            //   const { proposerdetail, proposerfdetail } = applicationData
            //   proposerdetail.forEach((e) => {
            //     personMap.set(e.Name, e.IDCards)
            //   })
            //   proposerfdetail.forEach((e) => {
            //     personMap.set(e.FName, e.FIDCard)
            //   })
            //   getCompareMZHH({
            //     UserID: this.$store.getters.userid,
            //     names: [...personMap.keys()].join(','),
            //     idcards: [...personMap.values()].join(',')
            //   })
            //     .then((deadRes) => {
            //       const { type, msg } = deadRes
            //       if (type === 0) {
            //         this.$message.success(msg)
            //         this.handlePostApplication(applicationData, res[1])
            //       } else {
            //         this.$error({
            //           title: '提示',
            //           content: msg
            //         })
            //       }
            //     })
            //     .finally(() => {
            //       this.$loading.hide()
            //     })
            // } else {
            //   this.handlePostApplication(applicationData, res[1])
            // }
            // this.handlePostApplication(applicationData, res[1])
            this.handleChangePost(applicationData, res[1])
          })
          .catch((err) => {
            this.$message.error({
              text: err,
            })
          })
      }
    },
    handlePostApplication(applicationData) {
      this.isSubmiting = true
      postApplication({
        ProposerModules: applicationData,
        State: 'update',
      })
        .then(() => {
          this.$eventBus.$emit('cityAuditRefresh')
          // this.handleChangePost(changeData)
        })
        .catch(() => {
          this.isSubmiting = false
          this.$message.error('异动修改失败，请重试')
        })
    },
    // 异动提交
    handleChangePost(applicationData, values) {
      const { AlterType, AlterInfo, AlterReasonQuit, AlterReasonChange, AlterDate, AlterExecutor } = values
      let AlterReason = ''
      if (AlterType === '退出') {
        if (AlterReasonQuit) {
          AlterReason = '中天共有产权退出'
        }
      } else if (AlterType === '变更') {
        AlterReason = AlterReasonChange.join(',')
      }
      const data = {
        State: 'AlterAudit',
        ProposerModules: {
          // ID: this.data.ID,
          ID: this.browserCacheObj.id,
          // ApplyNO: this.data.ApplyNo,
          ApplyNO: this.browserCacheObj.ApplyNo,
          AlterType,
          AlterInfo,
          AlterReason: AlterReason,
          AlterDate,
          AlterExecutor,
          LastAlterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
          LastAlterUserID: this.$store.getters.userid,
          SelectAlterGroup: this.selectedRowKeys.join(','),
        },
      }
      postProposerExamine(data)
        .then((res) => {
          this.$message.success('异动修改成功')
          this.$emit('change')
          this.handlePostApplication(applicationData)
          // this.close()
          // this.$loading.hide()
          this.$multiTab.closeCurrentPage()
        })
        .catch(() => {
          this.$message.error('异动修改失败，请重试')
        })
        .finally(() => {
          this.isSubmiting = false
        })
    },
    hanldeAfterClose() {},
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-select {
  width: 100%;
}
</style>
